package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.OmcServiceOrderMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.constant.ServiceOrderCommentMessageConstant;
import com.csun.cmny.provider.model.constant.ServiceOrderConstant;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.*;
import com.csun.cmny.provider.model.dto.service.*;
import com.csun.cmny.provider.model.vo.*;
import com.csun.cmny.provider.model.vo.service.ServiceCountStatusVo;
import com.csun.cmny.provider.model.vo.service.ServiceOrderCommentVo;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.BaiduMapUtils;
import com.csun.cmny.provider.utils.JPushService;
import com.csun.cmny.provider.utils.LocationUtils;
import com.csun.cmny.provider.utils.SerialNumberUtil;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.csun.cmny.provider.model.constant.ServiceOrderConstant.ORDER_STATUS_ENSURE;
import static com.csun.cmny.provider.model.constant.ServiceOrderConstant.ORDER_STATUS_WAIT;

@Service
@Slf4j
@Transactional
public class OmcServiceOrderServiceImpl extends BaseService<OmcServiceOrder> implements OmcServiceOrderService {

    @Resource
    private OmcServiceOrderMapper omcServiceOrderMapper;
    @Resource
    private SerialNumberUtil serialNumberUtil;
    @Resource
    private OmcMerchandiseService omcMerchandiseService;
    @Resource
    private OmcServiceOrderItemService omcServiceOrderItemService;
    @Resource
    private JPushService jpushService;
    @Resource
    private UacRpcService uacRpcService;
    @Resource
    private OpcMessageService opcMessageService;
    @Resource
    private OpcWebSocketService opcWebSocketService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private OmcServiceSecondLevelService omcServiceSecondLevelService;
    @Resource
    private OmcServiceOrderCommentService omcServiceOrderCommentService;
    @Resource
    private OmcServiceOrderCommentService commentService;
    @Resource
    private OmcServiceSecondLevelService secondLevelService;
    @Resource
    private OmcServiceFirstLevelService firstLevelService;
    @Resource
    private OldmanService oldmanService;

    @Override
    public String addServiceOrder(ServiceOrderDto serviceOrderDto, LoginAuthDto loginAuthDto) {

        //校验商家
        UacMerchant merchant = (UacMerchant) redisTemplate.opsForValue().get(RedisKeyUtil.getUacMerchant(serviceOrderDto.getMerchantId().toString()));
        if (PublicUtil.isEmpty(merchant)){
            throw new OmcBizException(ErrorCodeEnum.OMC10080020);
        }

        OmcServiceOrder omcServiceOrder = new OmcServiceOrder();
        BeanUtils.copyProperties(serviceOrderDto, omcServiceOrder);

       // int isOnline = uacRpcService.checkMerchantOnline(serviceOrderDto.getMerchantId());
        int isOnline = merchant.getIsBusiness();
        if(isOnline != 1){
            throw new OmcBizException(ErrorCodeEnum.OMC10080017);
        }

        Oldman oldman = new Oldman();
        oldman.setOldmanId(serviceOrderDto.getOldmanId().intValue());
        Oldman omcOldMan = oldmanService.selectByOld(oldman);
        if (PublicUtil.isEmpty(omcOldMan)){
            throw new OmcBizException(ErrorCodeEnum.OMC10031017);
        }

        //校验商品
        List<ServiceOrderItemDto> serviceOrderItemList = serviceOrderDto.getServiceOrderItemList();
        if(serviceOrderItemList.size() < 1){
            throw new OmcBizException(ErrorCodeEnum.OMC10037015);
        }

        omcServiceOrder.setUpdateInfo(loginAuthDto);
        omcServiceOrder.setOrderNo(serialNumberUtil.getSerialNumberString());
        //订单未支付
        omcServiceOrder.setIsPayed(ServiceOrderConstant.ORDER_UNPAYED);
        //订单待接单
        omcServiceOrder.setOrderStatus(ORDER_STATUS_WAIT);

        Map<Long, Integer> merchantDiseMap = serviceOrderItemList.stream().collect(Collectors.toMap(ServiceOrderItemDto::getId, ServiceOrderItemDto::getNumber));

        List<MerchandiseVo> merchandiseVos = omcMerchandiseService.selectByIdList(Lists.newArrayList(merchantDiseMap.keySet()));

        if(merchandiseVos.size() != serviceOrderItemList.size()){
            throw new OmcBizException(ErrorCodeEnum.OMC10031002);
        }
        
        BigDecimal total = BigDecimal.ZERO;
        Long serviceType = null;
        BigDecimal amountCommission=BigDecimal.ZERO;

        List<OmcServiceOrderItem> itemList = Lists.newArrayList();
        for(MerchandiseVo vo : merchandiseVos){

            //包含下架商品
            if (vo.getIsPutaway()!=0){
                throw new OmcBizException(ErrorCodeEnum.OMC10080037);
            }

            OmcServiceOrderItem item = new OmcServiceOrderItem();
            item.setName(vo.getMerchandiseName());
            item.setDescription(vo.getParticulars());
            item.setNumber(merchantDiseMap.get(vo.getId()));
            item.setPrice(vo.getUnitPrice());
            item.setServiceThiredLevelId(vo.getId());
            total = total.add(vo.getUnitPrice().multiply(new BigDecimal(merchantDiseMap.get(vo.getId()))));
            itemList.add(item);

            //计算佣金金额
            BigDecimal number = new BigDecimal(merchantDiseMap.get(vo.getId()));
            BigDecimal proportion = new BigDecimal(vo.getServiceFee()).divide(new BigDecimal(100));
            BigDecimal money = number.multiply(vo.getUnitPrice()).multiply(proportion);

            amountCommission=amountCommission.add(money);




            if(PublicUtil.isEmpty(serviceType)){
                serviceType = vo.getSecondLevellId();
            }else if (!serviceType.equals(vo.getSecondLevellId())) {
                throw new OmcBizException(ErrorCodeEnum.OMC10080016);
            }
        }




        Date serviceSubscribeTime=null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            serviceSubscribeTime = simpleDateFormat.parse(serviceOrderDto.getServiceSubscribeTime());
        } catch (ParseException e) {
            throw new OmcBizException(ErrorCodeEnum.OMC10080021);
        }


        OmcServiceSecondLevel secondLevel = secondLevelService.selectByKey(serviceType);
        if (PublicUtil.isEmpty(secondLevel)){
            throw new OmcBizException(ErrorCodeEnum.OMC10080036);
        }
        OmcServiceFirstLevel firstLevel = firstLevelService.selectByKey(secondLevel.getFirstLevelId());
        if (PublicUtil.isEmpty(firstLevel)){
            throw new OmcBizException(ErrorCodeEnum.OMC10080036);
        }



        //写入订单数据
        omcServiceOrder.setUserIdPut(loginAuthDto.getUserId());
        omcServiceOrder.setUserNamePut(loginAuthDto.getUserName());
        omcServiceOrder.setLongitude(new BigDecimal(serviceOrderDto.getLongitude()));
        omcServiceOrder.setLatitude(new BigDecimal(serviceOrderDto.getLatitude()));
        omcServiceOrder.setServiceSubscribeTime(serviceSubscribeTime);
        omcServiceOrder.setAmountCommission(amountCommission);
        omcServiceOrder.setServiceSecondLevelId(serviceType);
        omcServiceOrder.setServiceSecondLevelName(secondLevel.getSecondLevelName());
        omcServiceOrder.setServiceFirstLevelId(firstLevel.getId());
        omcServiceOrder.setServiceFirstLevelName(firstLevel.getName());
        omcServiceOrder.setTotal(total);
        omcServiceOrder.setMerchantId(serviceOrderDto.getMerchantId());
        omcServiceOrder.setMerchantName(merchant.getMerchantName());
        omcServiceOrder.setOldmanName(omcOldMan.getOldName());

        int ret = omcServiceOrderMapper.insertSelective(omcServiceOrder);
        if(ret > 0){
            itemList.forEach(i -> i.setServiceOrderId(omcServiceOrder.getId()));
            omcServiceOrderItemService.batchSave(itemList);
        }

        List<RpcMerchantVO> rpcMerchantVOS = uacRpcService.queryMerchantListByIdList(Lists.newArrayList(serviceOrderDto.getMerchantId()));
        if(rpcMerchantVOS.size() < 1){
            throw new OmcBizException(ErrorCodeEnum.OMC10080020);
        }

        //新增批注
        OmcServiceOrderComment omcServiceOrderComment = new OmcServiceOrderComment();
        omcServiceOrderComment.setServiceOrderId(omcServiceOrder.getId());
        omcServiceOrderComment.setMessage(ServiceOrderCommentMessageConstant.ORDER_STATUS_WAIT);
        omcServiceOrderComment.setUserId(loginAuthDto.getUserName());
        commentService.save(omcServiceOrderComment);

        //创建推送请求对象 老人入院填写基本信息
        SendMessageRequest sendMessageRequest = new SendMessageRequest();
        sendMessageRequest.setMsgCode(ServiceOrderConstant.MERCHANT_ORDER_NEED_ENSURE);
        sendMessageRequest.setUserIdList(Lists.newArrayList(rpcMerchantVOS.get(0).getUserId()));
        sendMessageRequest.setGroupId(loginAuthDto.getGroupId());
        opcMessageService.pushByUser(sendMessageRequest);


//        SendWebSocketRequest sendWebSocketRequest = new SendWebSocketRequest();
//        sendWebSocketRequest.setMsgType(ServiceOrderConstant.MERCHANT_ORDER_NEED_ENSURE);
//        sendWebSocketRequest.setMessage("您有新的订单");
//        sendWebSocketRequest.setRefNo(Long.toString(UniqueIdGenerator.generateId()));
//        sendWebSocketRequest.setGroupId(loginAuthDto.getGroupId());
//        sendWebSocketRequest.setUserIdList(Lists.newArrayList(serviceOrderDto.getMerchantId()));
//        sendWebSocketRequest.setMsgType(WebSocketConstant.WEBSOCKET_WITH_USER_ID_LIST);
//        opcWebSocketService.sendWebSocketMessage(sendWebSocketRequest);

        //推送
//        Map<String, Object> map = Maps.newHashMap();
//        List<String> tagList = Lists.newArrayList();
//        tagList.add(JiGuangConstant.TAG_MARCHANT);
//        log.info("=======================> recv order tagList = {}", tagList);
//        // 推送 -- 通知商家
//        map.put("msgType", "orderPut");
//        map.put("oldmanName", omcServiceOrder.getOldmanName());
//        map.put("serviceName", omcServiceOrder.getMerchantName());
//        map.put("serviceAddress", omcServiceOrder.getServiceAddress());
//        jpushService.sendToAll(Constant.ORDER_MESSAGE_WAIT,
//                Constant.ORDER_MESSAGE_WAIT,
//                Constant.ORDER_MESSAGE_WAIT, JSONObject.fromObject(map).toString(), tagList);

        return omcServiceOrder.getId().toString();
    }

    @Override
    public Integer getServiceOrder(GetOrderDto getOrderDto, LoginAuthDto loginAuthDto) {

        OmcServiceOrder omcServiceOrderQuery = omcServiceOrderMapper.selectByPrimaryKey(getOrderDto.getId());
        if (PublicUtil.isEmpty(omcServiceOrderQuery)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }

        if (!omcServiceOrderQuery.getOrderStatus().equals(ORDER_STATUS_ENSURE)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032021);
        }

        /*计算预计所需送达时间*/
        BigDecimal zero = BigDecimal.ZERO;
        //配送地址纬度
        BigDecimal deliveryLatitude = omcServiceOrderQuery.getLatitude();
        //配送地址经度
        BigDecimal deliveryLongitude = omcServiceOrderQuery.getLongitude();
        //配送人员经度
        BigDecimal staffLongitude = new BigDecimal(getOrderDto.getStaffLongitude());
        //配送人员纬度
        BigDecimal staffLatitude = new BigDecimal(getOrderDto.getStaffLatitude());
        UacMerchant merchant = (UacMerchant) redisTemplate.opsForValue().get(RedisKeyUtil.getUacMerchant(omcServiceOrderQuery.getMerchantId().toString()));


        if (!deliveryLatitude.equals(zero)&&!deliveryLongitude.equals(zero)){

            //服务人员从商家到配送地址的时间
            int toDetailed = BaiduMapUtils.timeByDistance(deliveryLongitude.doubleValue() , deliveryLatitude.doubleValue(),merchant.getLongitude().doubleValue(), merchant.getLatitude().doubleValue());


            //服务人员到商家的时间
            int toMerchant = BaiduMapUtils.timeByDistance(merchant.getLongitude().doubleValue(), merchant.getLatitude().doubleValue(), staffLongitude.doubleValue(), staffLatitude.doubleValue());

            if (toDetailed!=0&&toMerchant!=0){
                int min=(toDetailed+toMerchant)/60;

                //当前时间
                Calendar theDate = Calendar.getInstance();
                theDate.setTime(new Date());
                theDate.add(Calendar.MINUTE,min);


                omcServiceOrderQuery.setEstimateTime(theDate.getTime());
            }

        }

        //新增批注
        OmcServiceOrderComment omcServiceOrderComment = new OmcServiceOrderComment();
        omcServiceOrderComment.setServiceOrderId(getOrderDto.getId());
        omcServiceOrderComment.setUserId(loginAuthDto.getUserName());
        omcServiceOrderComment.setMessage(ServiceOrderCommentMessageConstant.ORDER_STATUS_RECEIVE);
        commentService.save(omcServiceOrderComment);


        //更改订单状态
        omcServiceOrderQuery.setUserIdGet(loginAuthDto.getUserId());
        omcServiceOrderQuery.setUserNameGet(loginAuthDto.getUserName());
        omcServiceOrderQuery.setUpdateTime(new Date());
        omcServiceOrderQuery.setOrderStatus(ServiceOrderConstant.ORDER_STATUS_RECEIVE);

        return omcServiceOrderMapper.updateByPrimaryKeySelective(omcServiceOrderQuery);
    }




    @Override
    public Integer assignServiceOrder(GetOrderByAssignDto getOrderDto, LoginAuthDto loginAuthDto) {

        OmcServiceOrder omcServiceOrderQuery = omcServiceOrderMapper.selectByPrimaryKey(getOrderDto.getId());
        if (PublicUtil.isEmpty(omcServiceOrderQuery)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }

        if (omcServiceOrderQuery.getOrderStatus().equals(ORDER_STATUS_WAIT)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10080006);
        }

        if(omcServiceOrderQuery.getOrderStatus().equals(ServiceOrderConstant.ORDER_STATUS_CANCEL)){
            throw new OmcBizException(ErrorCodeEnum.OMC10080011);
        }

        if(omcServiceOrderQuery.getOrderStatus().equals(ServiceOrderConstant.ORDER_STATUS_COMPELETE)){
            throw new OmcBizException(ErrorCodeEnum.OMC10080012);
        }

        if (PublicUtil.isEmpty(omcServiceOrderQuery.getUserIdGet())) {
            omcServiceOrderQuery.setUserIdGet(getOrderDto.getUserIdGet());
            omcServiceOrderQuery.setUserNameGet(getOrderDto.getUserNameGet());
            omcServiceOrderQuery.setUpdateTime(new Date());
            omcServiceOrderQuery.setOrderStatus(ServiceOrderConstant.ORDER_STATUS_RECEIVE);
        } else {
            omcServiceOrderQuery.setChangeIdGet(getOrderDto.getUserIdGet());
            omcServiceOrderQuery.setChangeNameGet(getOrderDto.getUserNameGet());
            omcServiceOrderQuery.setUpdateTime(new Date());
            omcServiceOrderQuery.setOrderStatus(ServiceOrderConstant.ORDER_STATUS_RECEIVE);
        }

        if(StringUtils.isNotEmpty(getOrderDto.getRemark())){
            omcServiceOrderQuery.setRemark(omcServiceOrderQuery.getChangeNameGet() + ";" + getOrderDto.getRemark());
        }

        return omcServiceOrderMapper.updateByPrimaryKeySelective(omcServiceOrderQuery);
    }

    @Override
    public Integer retreatServiceOrder(Long orderId, LoginAuthDto loginAuthDto) {

        OmcServiceOrder omcServiceOrderQuery = omcServiceOrderMapper.selectByPrimaryKey(orderId);
        if (PublicUtil.isEmpty(omcServiceOrderQuery)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }

        if (omcServiceOrderQuery.getOrderStatus().equals(ServiceOrderConstant.ORDER_STATUS_CANCEL)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10080014);
        }
        if (omcServiceOrderQuery.getOrderStatus().equals(ServiceOrderConstant.ORDER_STATUS_COMPELETE)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10080015);
        }
        //已支付的订单不可以取消
        if (omcServiceOrderQuery.getIsPayed()!=ServiceOrderConstant.ORDER_UNPAYED){
            throw new OmcBizException(ErrorCodeEnum.OMC10080044);
        }

        //新增批注
        OmcServiceOrderComment omcServiceOrderComment = new OmcServiceOrderComment();
        omcServiceOrderComment.setUserId(loginAuthDto.getUserName());
        omcServiceOrderComment.setServiceOrderId(orderId);
        omcServiceOrderComment.setMessage(ServiceOrderCommentMessageConstant.ORDER_STATUS_CANCEL);
        commentService.save(omcServiceOrderComment);

        omcServiceOrderQuery.setOrderStatus(ServiceOrderConstant.ORDER_STATUS_CANCEL);

        return omcServiceOrderMapper.updateByPrimaryKeySelective(omcServiceOrderQuery);
    }

    @Override
    public Integer retreatServiceOrderByTaker(Long orderId, LoginAuthDto loginAuthDto) {
        OmcServiceOrder omcServiceOrder = selectByKey(orderId);
        if (PublicUtil.isEmpty(omcServiceOrder)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }
        if (!omcServiceOrder.getOrderStatus().equals(ServiceOrderConstant.ORDER_STATUS_RECEIVE)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10080041);
        }
        if (!omcServiceOrder.getUserIdGet().equals(loginAuthDto.getUserId())){
            throw new OmcBizException(ErrorCodeEnum.OMC10080042);
        }
        omcServiceOrder.setOrderStatus(ServiceOrderConstant.ORDER_STATUS_ENSURE);
        return update(omcServiceOrder);
    }

    @Override
    public Integer completeServiceOrder(Long orderId, LoginAuthDto loginAuthDto) {

        OmcServiceOrder omcServiceOrderQuery = omcServiceOrderMapper.selectByPrimaryKey(orderId);
        if (PublicUtil.isEmpty(omcServiceOrderQuery)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }
        if (!omcServiceOrderQuery.getOrderStatus().equals(ServiceOrderConstant.ORDER_STATUS_CHECK_OUT)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10080043);
        }
        if(omcServiceOrderQuery.getIsPayed() != ServiceOrderConstant.ORDER_PAYED){
            throw new OmcBizException(ErrorCodeEnum.OMC10080008);
        }

        //新增批注
        OmcServiceOrderComment omcServiceOrderComment = new OmcServiceOrderComment();
        omcServiceOrderComment.setServiceOrderId(orderId);
        omcServiceOrderComment.setUserId(loginAuthDto.getUserName());
        omcServiceOrderComment.setMessage(ServiceOrderCommentMessageConstant.ORDER_STATUS_COMPELETE);

        //删除redis中的服务人员地址信息
        //redisTemplate.delete(RedisKeyUtil.getOmcRealTimeOrderPositioning(orderId.toString()));

        //更改订单状态
        omcServiceOrderQuery.setServiceEndTime(new Date());
        omcServiceOrderQuery.setOrderStatus(ServiceOrderConstant.ORDER_STATUS_COMPELETE);
        return omcServiceOrderMapper.updateByPrimaryKeySelective(omcServiceOrderQuery);
    }

    @Override
    public PageInfo listPage(ServiceOrderQueryDto serviceOrderQueryDto) {
        PageHelper.startPage(serviceOrderQueryDto.getPageNum(), serviceOrderQueryDto.getPageSize());
        List<ServiceOrderVO> voList = omcServiceOrderMapper.listPage(serviceOrderQueryDto);

        //写入批注
        for (ServiceOrderVO serviceOrderVO : voList) {

            List<ServiceOrderCommentVo>list=commentService.selectMessageByServiceOrderId(serviceOrderVO.getId());

            serviceOrderVO.setCommentList(list);
        }
        return new PageInfo<>(voList);
    }

    @Override
    public PageInfo listOrderPage(OmcAddressDto omcAddressDto) {
        if(omcAddressDto.getStatusList().contains(ORDER_STATUS_WAIT)||omcAddressDto.getStatusList().contains(ORDER_STATUS_ENSURE))   omcAddressDto.setUserIdGet((long) -1);
        List<ServicePendingOrderVo> voList=omcServiceOrderMapper.listOrderPage(omcAddressDto);

        for (ServicePendingOrderVo vo : voList) {
            //根据地址计算与下单人距离
            vo.setDistanceToOrder(LocationUtils.getDistance(vo.getOldmanAddressLongitude().doubleValue(),vo.getOldmanAddressLatitude().doubleValue(),omcAddressDto.getLongitude(),omcAddressDto.getLatitude()));

            if(PublicUtil.isEmpty(vo.getMerchantId()))    continue;
            //获取商家的地址
            String rediskey=RedisKeyUtil.getUacMerchant(vo.getMerchantId().toString());
            UacMerchant merchant = (UacMerchant) redisTemplate.opsForValue().get(rediskey);
            if(PublicUtil.isEmpty(merchant))    continue;
            vo.setMerchantName(merchant.getMerchantName());
            vo.setMerchantAddress(merchant.getAddress());
            vo.setMerchantAddressLongitude(merchant.getLongitude());
            vo.setMerchantAddressLatitude(merchant.getLatitude());
            //根据地址计算距离
            vo.setDistanceToMerchant(LocationUtils.getDistance(merchant.getLongitude().doubleValue(),merchant.getLatitude().doubleValue(),omcAddressDto.getLongitude(),omcAddressDto.getLatitude()));
        }

        return new PageInfo<>(voList);
    }

    @Override
    public PageInfo listServicedOrder(OmcServicedOrderDto omcServicedOrderDto) {
        List<ServicedOrderVo> voList = omcServiceOrderMapper.listServicedPage(omcServicedOrderDto);

        //计算总价
        Double sum=0.0;
        for(ServicedOrderVo vo : voList){
            sum+=vo.getTotal();
        }

        for(ServicedOrderVo vo : voList){
            if(PublicUtil.isEmpty(vo.getMerchantId()))    continue;
            //获取商家的地址
            String rediskey=RedisKeyUtil.getUacMerchant(vo.getMerchantId().toString());
            UacMerchant merchant = (UacMerchant) redisTemplate.opsForValue().get(rediskey);
            if(PublicUtil.isEmpty(merchant))    continue;
            vo.setMerchantName(merchant.getMerchantName());
            vo.setMerchantAddress(merchant.getAddress());

            vo.setSumTotal(sum);
        }

        return new PageInfo<>(voList);
    }

    @Override
    public Double getTotalCommission(OmcServicedOrderDto omcServicedOrderDto) {
        omcServicedOrderDto.setStatus(ServiceOrderConstant.ORDER_STATUS_COMPELETE);
        omcServicedOrderDto.setId((long) 0);

        List<ServicedOrderVo> voList = omcServiceOrderMapper.listServicedPage(omcServicedOrderDto);

        Double sum=0.0;
        for(ServicedOrderVo vo:voList){
            sum+=vo.getAmountCommission().doubleValue();
        }

        return sum;
    }

    @Override
    public ServiceOrderVO detail(Long orderId, LoginAuthDto loginAuthDto) {

        OmcServiceOrder omcServiceOrderQuery = omcServiceOrderMapper.selectByPrimaryKey(orderId);
        if (PublicUtil.isEmpty(omcServiceOrderQuery)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }

        ServiceOrderVO serviceOrderVO = new ServiceOrderVO();
        BeanUtils.copyProperties(omcServiceOrderQuery,serviceOrderVO);

        if (PublicUtil.isNotEmpty(omcServiceOrderQuery.getServiceSubscribeTime())){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            serviceOrderVO.setServiceSubscribeTime(simpleDateFormat.format(omcServiceOrderQuery.getServiceSubscribeTime()));
        }
        OmcServiceOrderItem itemQuery = new OmcServiceOrderItem();
        itemQuery.setServiceOrderId(omcServiceOrderQuery.getId());
        List<OmcServiceOrderItem> itemList = omcServiceOrderItemService.select(itemQuery);

        if(itemList.size() > 0){
            List<ServiceOrderItemVO> voList = Lists.newArrayList();
            itemList.forEach(item -> {
                ServiceOrderItemVO vo = new ServiceOrderItemVO();
                BeanUtils.copyProperties(item,vo);
                voList.add(vo);
            });
            for (ServiceOrderItemVO serviceOrderItemVO : voList) {
                OmcMerchandise merchandise = omcMerchandiseService.selectByKey(serviceOrderItemVO.getServiceThiredLevelId());
                serviceOrderItemVO.setImgsCode(merchandise.getImgsCode());
            }
            serviceOrderVO.setItemList(voList);
        }

        if (PublicUtil.isNotEmpty(omcServiceOrderQuery.getUserIdGet())){
            ServiceOrderUploadThePositioningDto positioningDto = new ServiceOrderUploadThePositioningDto();
            if (PublicUtil.isNotEmpty(omcServiceOrderQuery.getChangeIdGet())){
                positioningDto = (ServiceOrderUploadThePositioningDto) redisTemplate.opsForValue().get(RedisKeyUtil.getOmcRealTimeOrderPositioning(omcServiceOrderQuery.getChangeIdGet().toString()));
            }else {
                positioningDto = (ServiceOrderUploadThePositioningDto) redisTemplate.opsForValue().get(RedisKeyUtil.getOmcRealTimeOrderPositioning(omcServiceOrderQuery.getUserIdGet().toString()));
            }

            if (PublicUtil.isNotEmpty(positioningDto)){
                serviceOrderVO.setStaffLongitude(positioningDto.getStaffLongitude());
                serviceOrderVO.setStaffLatitude(positioningDto.getStaffLatitude());
            }
        }

        //写入批注
        List<ServiceOrderCommentVo> list=commentService.selectMessageByServiceOrderId(orderId);
        serviceOrderVO.setCommentList(list);


        return serviceOrderVO;
    }

    @Override
    public ServiceOrderDetailsVo orderDetail(Long orderId, LoginAuthDto loginAuthDto) {
        OmcServiceOrder omcServiceOrderQuery = omcServiceOrderMapper.selectByPrimaryKey(orderId);
        if (PublicUtil.isEmpty(omcServiceOrderQuery)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }

        OmcServiceOrderItem omcServiceOrderItem = new OmcServiceOrderItem();
        omcServiceOrderItem.setServiceOrderId(orderId);
        List<OmcServiceOrderItem> omcServiceOrderItems = omcServiceOrderItemService.select(omcServiceOrderItem);
        ServiceOrderDetailsVo serviceOrderDetailsVo = new ServiceOrderDetailsVo();
        serviceOrderDetailsVo.setOrderNo(omcServiceOrderQuery.getOrderNo());
        serviceOrderDetailsVo.setStatus(omcServiceOrderQuery.getOrderStatus());
        serviceOrderDetailsVo.setOmcServiceOrderItems(omcServiceOrderItems);

        //写入批注
        List<ServiceOrderCommentVo> list=commentService.selectMessageByServiceOrderId(orderId);
        serviceOrderDetailsVo.setCommentList(list);
        return serviceOrderDetailsVo;
    }

    @Override
    public Integer ensure(Long orderId, LoginAuthDto loginAuthDto) {

        OmcServiceOrder omcServiceOrderQuery = omcServiceOrderMapper.selectByPrimaryKey(orderId);
        if (PublicUtil.isEmpty(omcServiceOrderQuery)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }

        if (!omcServiceOrderQuery.getOrderStatus().equals(ORDER_STATUS_WAIT)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10032021);
        }

        //推送
//        Map<String, Object> map = Maps.newHashMap();
//        List<String> tagList = Lists.newArrayList();
//        tagList.add(JiGuangConstant.TAG_MARCHANT);
//        log.info("=======================> recv order tagList = {}", tagList);
//        // 推送 -- 通知商家
//        map.put("msgType", "orderPut");
//        map.put("oldmanName", omcServiceOrderQuery.getOldmanName());
//        map.put("serviceName", omcServiceOrderQuery.getMerchantName());
//        map.put("serviceAddress", omcServiceOrderQuery.getServiceAddress());
//        jpushService.sendToAll(Constant.ORDER_MESSAGE_WAIT,
//                Constant.ORDER_MESSAGE_WAIT,
//                Constant.ORDER_MESSAGE_WAIT, JSONObject.fromObject(map).toString(), tagList);


        //新增批注
        OmcServiceOrderComment omcServiceOrderComment = new OmcServiceOrderComment();
        omcServiceOrderComment.setUserId(loginAuthDto.getUserName());
        omcServiceOrderComment.setServiceOrderId(orderId);
        omcServiceOrderComment.setMessage(ServiceOrderCommentMessageConstant.ORDER_STATUS_ENSURE);
        commentService.save(omcServiceOrderComment);


        omcServiceOrderQuery.setOrderStatus(ORDER_STATUS_ENSURE);
        return omcServiceOrderMapper.updateByPrimaryKeySelective(omcServiceOrderQuery);
    }

    @Override
    public List<OrderCountVO> orderCount(CountQueryDTO countQueryDTO) {
        return omcServiceOrderMapper.orderCount(countQueryDTO);
    }

    @Override
    public List<MerchantCountVO> merchantCount(CountQueryDTO countQueryDTO) {

        List<MerchantCountVO> voList = omcServiceOrderMapper.merchantCount(countQueryDTO);
        if(voList.size() > 0){
            List<Long> merchantIdList = voList.stream().map(v -> v.getMerchantId()).collect(Collectors.toList());
            List<RpcMerchantVO> rpcUserVos = uacRpcService.queryMerchantListByIdList(merchantIdList);

            if(rpcUserVos.size() > 0){
                for (RpcMerchantVO rpcMerchantVO : rpcUserVos) {
                    for (MerchantCountVO merchantCountVO : voList) {
                        if(rpcMerchantVO.getId().equals(merchantCountVO.getMerchantId())){
                            merchantCountVO.setMerchantName(rpcMerchantVO.getMerchantName());
                        }
                    }
                }
            }
        }

        return voList;
    }


    @Override
    public List<ServiceOrderVO> showWaitServiceTask(ServiceOrderQueryDto serviceOrderQueryDto,LoginAuthDto loginAuthDto) {




        List<Integer> statusList = Lists.newArrayList();
        statusList.add(ServiceOrderConstant.ORDER_STATUS_RECEIVE);
        statusList.add(ServiceOrderConstant.ORDER_STATUS_CHECK_IN);
        statusList.add(ServiceOrderConstant.ORDER_STATUS_CHECK_OUT);

        serviceOrderQueryDto.setStatusList(statusList);
        serviceOrderQueryDto.setUserIdGet(loginAuthDto.getUserId());

        List<ServiceOrderVO> serviceOrderVOS = omcServiceOrderMapper.listPage(serviceOrderQueryDto);



        //写入批注
        for (ServiceOrderVO serviceOrderVO : serviceOrderVOS) {

            List<ServiceOrderCommentVo>list=commentService.selectMessageByServiceOrderId(serviceOrderVO.getId());

            serviceOrderVO.setCommentList(list);
        }

        return serviceOrderVOS;
    }

    /**
     * 助餐 - 到店打卡
     *
     * @param
     * @return
     */
    @Override
    public Integer checkInById(ServiceOrderOperationDto serviceOrderOperationDto, LoginAuthDto loginAuthDto) {

        // 查询服务订单
        OmcServiceOrder omcServiceOrder = selectByKey(serviceOrderOperationDto.getId());

        if (PublicUtil.isEmpty(omcServiceOrder)){
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }

        // 判断订单状态
        if (omcServiceOrder.getOrderStatus()!=ServiceOrderConstant.ORDER_STATUS_RECEIVE){
            throw new OmcBizException(ErrorCodeEnum.OMC10032030);
        }
        //判断是否是本人订单
        if (PublicUtil.isNotEmpty(omcServiceOrder.getChangeIdGet())){
            if (!omcServiceOrder.getChangeIdGet().equals(loginAuthDto.getUserId())){
                throw new OmcBizException(ErrorCodeEnum.OMC10032031);
            }
        }else {
            if (!omcServiceOrder.getUserIdGet().equals(loginAuthDto.getUserId())){
                throw new OmcBizException(ErrorCodeEnum.OMC10032031);
            }
        }

        omcServiceOrder.setOrderStatus(ServiceOrderConstant.ORDER_STATUS_CHECK_IN);

        // 判断订单状态

        // 新增批注
        OmcServiceOrderComment omcServiceOrderComment = new OmcServiceOrderComment();
        if (PublicUtil.isNotEmpty(serviceOrderOperationDto.getImgCode())){
            omcServiceOrderComment.setImgCode(serviceOrderOperationDto.getImgCode());
        }
        if (PublicUtil.isNotEmpty(serviceOrderOperationDto.getRemark())){
            omcServiceOrderComment.setRemark(serviceOrderOperationDto.getRemark());
        }
        omcServiceOrderComment.setServiceOrderId(serviceOrderOperationDto.getId());
        omcServiceOrderComment.setUserId(loginAuthDto.getUserName());
        omcServiceOrderComment.setMessage(ServiceOrderCommentMessageConstant.ORDER_STATUS_CHECK_IN);

        omcServiceOrderCommentService.save(omcServiceOrderComment);

        return omcServiceOrderMapper.updateByPrimaryKeySelective(omcServiceOrder);
    }

    /**
     * 服务完成打卡
     *
     * @param
     * @return
     */
    @Override
    public Integer checkOutById(ServiceOrderOperationDto serviceOrderOperationDto, LoginAuthDto loginAuthDto) {

        // 查询服务订单
        OmcServiceOrder omcServiceOrder = selectByKey(serviceOrderOperationDto.getId());

        if (PublicUtil.isEmpty(omcServiceOrder)){
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }

        // 判断订单状态
        if (omcServiceOrder.getOrderStatus()!=ServiceOrderConstant.ORDER_STATUS_CHECK_IN){
            throw new OmcBizException(ErrorCodeEnum.OMC10032032);
        }
        //判断是否是本人订单
        if (PublicUtil.isNotEmpty(omcServiceOrder.getChangeIdGet())){
            if (!omcServiceOrder.getChangeIdGet().equals(loginAuthDto.getUserId())){
                throw new OmcBizException(ErrorCodeEnum.OMC10032031);
            }
        }else {
            if (!omcServiceOrder.getUserIdGet().equals(loginAuthDto.getUserId())){
                throw new OmcBizException(ErrorCodeEnum.OMC10032031);
            }
        }

        // 判断服务类型
        omcServiceOrder.setOrderStatus(ServiceOrderConstant.ORDER_STATUS_CHECK_OUT);

        // 判断订单状态

        // 新增批注
        OmcServiceOrderComment omcServiceOrderComment = new OmcServiceOrderComment();
        if (PublicUtil.isNotEmpty(serviceOrderOperationDto.getImgCode())){
            omcServiceOrderComment.setImgCode(serviceOrderOperationDto.getImgCode());
        }
        if (PublicUtil.isNotEmpty(serviceOrderOperationDto.getRemark())){
            omcServiceOrderComment.setRemark(serviceOrderOperationDto.getRemark());
        }
        omcServiceOrderComment.setServiceOrderId(serviceOrderOperationDto.getId());
        omcServiceOrderComment.setUserId(loginAuthDto.getUserName());
        omcServiceOrderComment.setMessage(ServiceOrderCommentMessageConstant.ORDER_STATUS_CHECK_OUT);

        omcServiceOrderCommentService.save(omcServiceOrderComment);

        return omcServiceOrderMapper.updateByPrimaryKeySelective(omcServiceOrder);
    }

    @Override
    public List<ServiceCountStatusVo> selectOrderNumbersByStatus(ServiceOrderCountDto serviceOrderCountDto) {
        return omcServiceOrderMapper.selectOrderNumbersByStatus(serviceOrderCountDto);
    }

    @Override
    public List<ServiceCountStatusVo> selectlongRangeOrderNumbersByStatus(LongRangeServiceOrderCountDto longRangeServiceOrderCountDto) {
        return omcServiceOrderMapper.selectlongRangeOrderNumbersByStatus(longRangeServiceOrderCountDto);
    }

    @Override
    public int pay(Long id) {
        OmcServiceOrder omcServiceOrder = selectByKey(id);
        if (PublicUtil.isEmpty(omcServiceOrder)){
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }
        if (omcServiceOrder.getIsPayed()!= ServiceOrderConstant.ORDER_UNPAYED){
            throw new OmcBizException(ErrorCodeEnum.OMC10032035);
        }

        omcServiceOrder.setIsPayed(ServiceOrderConstant.ORDER_PAYED);
        return update(omcServiceOrder);
    }

    @Override
    public Integer selectHaveUnfinishedOrderNumbers(Long userId) {


        Integer isChantGet = omcServiceOrderMapper.selectHaveUnfinishedOrderNumbersIsChantGet(userId);

        if (isChantGet>0){

            return isChantGet;
        }
        Integer isUserGet = omcServiceOrderMapper.selectHaveUnfinishedOrderNumbersIsUserGet(userId);

        if (isUserGet>0){

            return isUserGet;
        }




        return 0;
    }

}
